package com.fu.shop.controller;

import com.fu.core.common.BusinessException;
import com.fu.core.common.ExceptionCode;
import com.fu.core.common.JsonResult;
import com.fu.core.pojo.Goods;
import com.fu.core.pojo.Picture;
import com.fu.core.pojo.Sku;
import com.fu.core.pojo.Type;
import com.fu.core.util.JsonUtil;
import com.fu.shop.service.GoodsService;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.hssf.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author 付龙江
 * @date 2022/1/28 22:34
 */
@RestController
@CrossOrigin
@RequestMapping("/goods")
@Api(tags = "后台商品管理")
public class GoodsController {

    GoodsService goodsService;

    @Autowired
    public GoodsController(GoodsService goodsService) {
        this.goodsService = goodsService;
    }

    @PostMapping(value = "/typeList")
    @ApiOperation(value = "分类管理")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "页码", dataType = "Integer", required = true),
            @ApiImplicitParam(name = "size", value = "每页条数", dataType = "Integer", required = true),
            @ApiImplicitParam(name = "typeName", value = "类型名称", dataType = "String", required = false)
    })
    public Map<String,Object> typeList(String typeName, Integer page, Integer size){

        PageInfo<Type> typeList = goodsService.selectTypeList(typeName, page, size);
        JsonResult jsonResult = new JsonResult();
        jsonResult.setCode("200");
        jsonResult.setField("total",typeList.getTotal());
        jsonResult.setField("typeList",typeList.getList());
        return jsonResult.getMap();
    }



    @PostMapping(value = "/updateOrAddType")
    @ApiOperation(value = "编辑分类/添加分类共用接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "typeId", value = "类型的编号(添加分类的时候不传)", dataType = "Integer", required = true),
            @ApiImplicitParam(name = "typeName", value = "类型名称", dataType = "String", required = true),
            @ApiImplicitParam(name = "typeParentId", value = "父级类型的编号", dataType = "Integer", required = true),
            @ApiImplicitParam(name = "typeImg", value = "图片的路径信息", dataType = "String", required = true),
            @ApiImplicitParam(name = "typeStatus", value = "类型状态0是隐藏  1是开启", dataType = "Integer", required = true),
            @ApiImplicitParam(name = "typeDetails", value = "类型描述", dataType = "String", required = true)
    })
    public Map<String,Object> updateOrAddType(Type type) throws Exception {
        goodsService.updateOrAddType(type);
        JsonResult jsonResult = new JsonResult();
        jsonResult.setCode("200");
        jsonResult.setMsg("修改成功");
        return jsonResult.getMap();
    }


    @PostMapping(value = "/updateTypeStatus")
    @ApiOperation(value = "隐藏或开启分类")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "typeId", value = "类型的编号", dataType = "Integer", required = true),
            @ApiImplicitParam(name = "typeStatus", value = "类型要改成的状态（隐藏0  显示1）", dataType = "Integer", required = true),
    })
    public Map<String,Object> updateTypeStatus(Integer typeId,Integer typeStatus) throws Exception {
        goodsService.updateTypeStatus(typeId, typeStatus);
        JsonResult jsonResult = new JsonResult();
        jsonResult.setCode("200");
        jsonResult.setMsg("隐藏或开启成功");
        return jsonResult.getMap();
    }

    @PostMapping(value = "/topTypeList")
    @ApiOperation(value = "顶级类型的下拉列表")
    public Map<String,Object> topTypeList(){
        List<Type> typeList = goodsService.topTypeList();
        JsonResult jsonResult = new JsonResult();
        jsonResult.setCode("200");
        jsonResult.setField("topTypeList",typeList);
        return jsonResult.getMap();
    }


    @PostMapping(value = "/goodsList")
    @ApiOperation(value = "商品管理")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "页码", dataType = "Integer", required = true),
            @ApiImplicitParam(name = "size", value = "每页条数", dataType = "Integer", required = true),
            @ApiImplicitParam(name = "goodsName", value = "商品名称", dataType = "String", required = false)
    })
    public Map<String,Object> goodsList(String goodsName, Integer page, Integer size){
        PageInfo<Map<String, Object>> mapPageInfo = goodsService.selectGoodsList(goodsName, page, size);
        JsonResult jsonResult = new JsonResult();
        jsonResult.setCode("200");
        jsonResult.setField("total",mapPageInfo.getTotal());
        jsonResult.setField("goodsList",mapPageInfo.getList());
        return jsonResult.getMap();
    }

    @PostMapping("/uploadGoodsList")
    @ApiOperation(value = "导出商品信息")
    public void uploadSpecificOrder(HttpServletResponse response)throws IOException {
        List<Map<String, Object>> list = goodsService.uploadGoodsList();
        //导出
        HSSFWorkbook workbook = new HSSFWorkbook();
        HSSFSheet sheet = workbook.createSheet("商品简略信息表");
        String fileName="商品简略信息表"+".xls";
        fileName = URLEncoder.encode(fileName, "utf-8").replaceAll("\\+", "%20");
        String[] headers = {"商品编号", "商品名称", "分类", "商品初始价格", "商品主图","初次上架时间", "商品状态"};
        // 创建一个行对象, 作为表头
        HSSFRow row = sheet.createRow(0);
        for (int i = 0; i < headers.length; i++) {
            // 在行中添加单元格
            HSSFCell cell = row.createCell(i);
            HSSFRichTextString text = new HSSFRichTextString(headers[i]);
            // 把字段名添加到表头行上
            cell.setCellValue(text);
        }
        int rowNum = 1;
        for (Map<String, Object> map : list) {
            HSSFRow dataRow = sheet.createRow(rowNum);
            dataRow.createCell(0).setCellValue(map.get("goodsId").toString());
            dataRow.createCell(1).setCellValue(map.get("goodsName").toString());
            dataRow.createCell(2).setCellValue(map.get("typeName").toString());
            dataRow.createCell(3).setCellValue(map.get("goodsStartPrice").toString());
            dataRow.createCell(4).setCellValue(map.get("goodsMainImg").toString());
            map.putIfAbsent("goodsStartShelf", "未上架");
            dataRow.createCell(5).setCellValue(map.get("goodsStartShelf").toString());
            dataRow.createCell(6).setCellValue(map.get("goodsStatus").toString());
            rowNum++;
        }
        //返回给前端下载
        response.setContentType("application/octet-stream");
        //附件格式打卡，不是打开页面
        response.setHeader("Content-disposition", "attachment;filename=" + fileName);
        response.flushBuffer();
        workbook.write(response.getOutputStream());
    }



    @PostMapping(value = "/updateGoodsStatus")
    @ApiOperation(value = "商品上下架")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "goodsId", value = "商品编号", dataType = "Integer", required = true),
            @ApiImplicitParam(name = "goodsStatus", value = "商品上下架状态（0 下架  1上架）", dataType = "Integer", required = true)
    })
    public Map<String,Object> updateGoodsStatus(Integer goodsId, Integer goodsStatus) throws Exception {
        goodsService.updateGoodsStatus(goodsId, goodsStatus);
        JsonResult jsonResult = new JsonResult();
        jsonResult.setCode("200");
        jsonResult.setMsg("上下架成功");
        return jsonResult.getMap();
    }

    @PostMapping(value = "/goodsDetail")
    @ApiOperation(value = "商品详情")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "goodsId", value = "商品编号", dataType = "Integer", required = true)
    })
    public Map<String,Object> goodsDetail(Integer goodsId) throws Exception {
        Map<String, Object> map = goodsService.selectGoodsDetails(goodsId);
        JsonResult jsonResult = new JsonResult();
        jsonResult.setCode("200");
        jsonResult.setField("map",map);
        return jsonResult.getMap();
    }


    @PostMapping(value = "/goodsDetailTypeList")
    @ApiOperation(value = "商品详情下的商品类型下拉列表")
    public Map<String,Object> goodsDetailTypeList(){
        List<Type> typeList = goodsService.goodsDetailTypeList();
        JsonResult jsonResult = new JsonResult();
        jsonResult.setCode("200");
        jsonResult.setField("topTypeList",typeList);
        return jsonResult.getMap();
    }





    @PostMapping(value = "/updateAndAddGoods")
    @ApiOperation(value = "编辑商品和添加商品")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "map", value = "传了商品id：就是编辑商品 没传就是添加", dataType = "map", required = true)
    })
    public Map<String,Object> updateAndAddGoods(@RequestBody Map<String,Object> map)throws Exception {
        if (map == null || map.size() < 1){
            throw new BusinessException(ExceptionCode.PARAMETER_PASSING_EXCEPTION);
        }
        //获取商品对象
        Object o = map.get("goods");
        if (StringUtils.isEmpty(o)){
            throw new BusinessException(ExceptionCode.GET_GOODS_FILED);
        }
        System.out.println(o);
        Goods goods = JsonUtil.stringToObject(JsonUtil.objectToString(o), Goods.class);
        //获取商品的sku信息
        List list = (List)map.get("skus");
        List<Sku> skus = new ArrayList<>();
        if (list == null || list.size() < 1){
            throw new BusinessException(ExceptionCode.GET_SKUS_FILED);
        }
        for (Object o1 : list) {
            skus.add(JsonUtil.stringToObject(JsonUtil.objectToString(o1),Sku.class));
        }
        //获取商品的特色图
        List listPic = (List)map.get("pictures");
        List<Picture> pictures = new ArrayList<>();
        if (listPic == null || listPic.size() < 1){
            throw new BusinessException(ExceptionCode.GET_PICTURES_FILED);
        }
        for (Object o1 : listPic) {
            pictures.add(JsonUtil.stringToObject(JsonUtil.objectToString(o1),Picture.class));
        }
        if (goods.getGoodsId() == null){
            //添加商品
            goodsService.addGoods(goods,skus,pictures);
        }else {
            //修改商品
            goodsService.updateGoods(goods,skus,pictures);
        }
        JsonResult jsonResult = new JsonResult();
        jsonResult.setCode("200");
        jsonResult.setField("map","添加或保存成功");
        return jsonResult.getMap();
    }


}
